package com.hzt.agprosaleplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzt.agprosaleplatform.common.CustomResponse;
import com.hzt.agprosaleplatform.entity.FinanceApplicationVO;
import com.hzt.agprosaleplatform.entity.Good;
import com.hzt.agprosaleplatform.entity.User;
import com.hzt.agprosaleplatform.service.AdminFinanceService;
import com.hzt.agprosaleplatform.service.AdminDashboardService;
import com.hzt.agprosaleplatform.service.AdminGoodsService;
import com.hzt.agprosaleplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = "http://localhost:5173")
public class AdminController {

    @Autowired
    private AdminFinanceService adminFinanceService;
    
    @Autowired
    private AdminDashboardService adminDashboardService;
    
    @Autowired
    private AdminGoodsService adminGoodsService;
    
    @Autowired
    private UserService userService;

    // 获取仪表盘统计数据
    @GetMapping("/dashboard/stats")
    public CustomResponse getDashboardStats() {
        try {
            Map<String, Object> stats = adminDashboardService.getDashboardStats();
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(stats);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取统计数据失败: " + e.getMessage());
            return response;
        }
    }
    
    // 获取近七天订单统计
    @GetMapping("/dashboard/orders/recent")
    public CustomResponse getRecentOrdersStats() {
        try {
            Map<String, Object> stats = adminDashboardService.getRecentOrdersStats();
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(stats);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取订单统计数据失败: " + e.getMessage());
            return response;
        }
    }
    
    // 获取近三个月订单统计
    @GetMapping("/dashboard/orders/recent-three-months")
    public CustomResponse getRecentThreeMonthsOrdersStats() {
        try {
            Map<String, Object> stats = adminDashboardService.getRecentThreeMonthsOrdersStats();
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(stats);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取订单统计数据失败: " + e.getMessage());
            return response;
        }
    }
    
    // 获取近七天营收统计
    @GetMapping("/dashboard/revenue/recent")
    public CustomResponse getRecentRevenueStats() {
        try {
            Map<String, Object> stats = adminDashboardService.getRecentRevenueStats();
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(stats);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取营收统计数据失败: " + e.getMessage());
            return response;
        }
    }
    
    // 获取商品统计
    @GetMapping("/dashboard/goods/stats")
    public CustomResponse getGoodsStats() {
        try {
            Map<String, Object> stats = adminDashboardService.getGoodsStats();
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(stats);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取商品统计数据失败: " + e.getMessage());
            return response;
        }
    }

    // 分页获取用户列表，支持搜索
    @GetMapping("/users")
    public CustomResponse getUsers(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String uid,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String role) {
        try {
            Page<User> page = new Page<>(pageNum, pageSize);
            IPage<User> userPage = userService.getUsersPage(page, uid, username, role);
            
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(userPage);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取用户列表失败: " + e.getMessage());
            return response;
        }
    }

    // 更新用户信息
    @PutMapping("/users/{uid}")
    public CustomResponse updateUser(@PathVariable String uid, @RequestBody User user) {
        try {
            boolean success = userService.updateUser(uid, user);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("用户信息更新成功");
            } else {
                response.setCode(500);
                response.setMessage("用户信息更新失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("用户信息更新失败: " + e.getMessage());
            return response;
        }
    }

    // 删除用户
    @DeleteMapping("/users/{uid}")
    public CustomResponse deleteUser(@PathVariable String uid) {
        try {
            boolean success = userService.deleteUser(uid);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("用户删除成功");
            } else {
                response.setCode(500);
                response.setMessage("用户删除失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("用户删除失败: " + e.getMessage());
            return response;
        }
    }

    // 获取所有申请
    @GetMapping("/finance/applications")
    public CustomResponse getAllApplications() {
        try {
            List<FinanceApplicationVO> applications = adminFinanceService.getAllApplications();
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(applications);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取失败");
            return response;
        }
    }

    // 通过申请
    @PostMapping("/finance/approve/{financeId}")
    public CustomResponse approveApplication(@PathVariable Integer financeId, @RequestBody Map<String, String> payload) {
        try {
            String opinion = payload.get("opinion");
            boolean success = adminFinanceService.approveApplication(financeId, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("通过成功");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败");
            return response;
        }
    }

    // 拒绝申请
    @PostMapping("/finance/reject/{financeId}")
    public CustomResponse rejectApplication(@PathVariable Integer financeId, @RequestBody Map<String, String> payload) {
        try {
            String opinion = payload.get("opinion");
            boolean success = adminFinanceService.rejectApplication(financeId, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("拒绝成功");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败");
            return response;
        }
    }

    // 放款
    @PostMapping("/finance/disburse/{financeId}")
    public CustomResponse disburseApplication(@PathVariable Integer financeId, @RequestBody Map<String, String> payload) {
        try {
            String opinion = payload.get("opinion");
            boolean success = adminFinanceService.disburseApplication(financeId, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("放款成功");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败");
            return response;
        }
    }
    
    // 还款
    @PostMapping("/finance/repay/{financeId}")
    public CustomResponse repayApplication(@PathVariable Integer financeId, @RequestBody Map<String, String> payload) {
        try {
            String opinion = payload.get("opinion");
            boolean success = adminFinanceService.repayApplication(financeId, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("还款成功");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败");
            return response;
        }
    }
    
    // 分页获取商品列表，支持搜索
    @GetMapping("/goods/list")
    public CustomResponse getGoodsList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String shopId,
            @RequestParam(required = false) String status) {
        try {
            Page<Good> page = new Page<>(pageNum, pageSize);
            IPage<Good> goodsPage = adminGoodsService.getGoodsPage(page, title, shopId, status);
            
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(goodsPage);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取商品列表失败: " + e.getMessage());
            return response;
        }
    }
    
    // 获取商品详情
    @GetMapping("/goods/{gid}")
    public CustomResponse getGoodsDetail(@PathVariable Integer gid) {
        try {
            Good goods = adminGoodsService.getGoodsDetail(gid);
            
            CustomResponse response = new CustomResponse();
            response.setCode(200);
            response.setData(goods);
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("获取商品详情失败: " + e.getMessage());
            return response;
        }
    }
    
    // 审核通过商品
    @PostMapping("/goods/approve")
    public CustomResponse approveGoods(@RequestBody Map<String, Object> payload) {
        try {
            Integer gid = (Integer) payload.get("gid");
            String opinion = (String) payload.get("opinion");
            
            boolean success = adminGoodsService.approveGoods(gid, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("商品审核通过");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败: " + e.getMessage());
            return response;
        }
    }
    
    // 拒绝商品
    @PostMapping("/goods/reject")
    public CustomResponse rejectGoods(@RequestBody Map<String, Object> payload) {
        try {
            Integer gid = (Integer) payload.get("gid");
            String opinion = (String) payload.get("opinion");
            
            boolean success = adminGoodsService.rejectGoods(gid, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("商品审核拒绝");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败: " + e.getMessage());
            return response;
        }
    }
    
    // 下架商品
    @PostMapping("/goods/offline")
    public CustomResponse offlineGoods(@RequestBody Map<String, Object> payload) {
        try {
            Integer gid = (Integer) payload.get("gid");
            String opinion = (String) payload.get("opinion");
            
            boolean success = adminGoodsService.offlineGoods(gid, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("商品下架成功");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败: " + e.getMessage());
            return response;
        }
    }
    
    // 上架商品
    @PostMapping("/goods/online")
    public CustomResponse onlineGoods(@RequestBody Map<String, Object> payload) {
        try {
            Integer gid = (Integer) payload.get("gid");
            String opinion = (String) payload.get("opinion");
            
            boolean success = adminGoodsService.onlineGoods(gid, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("商品上架成功");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败: " + e.getMessage());
            return response;
        }
    }
    
    // 删除商品
    @PostMapping("/goods/delete")
    public CustomResponse deleteGoods(@RequestBody Map<String, Object> payload) {
        try {
            Integer gid = (Integer) payload.get("gid");
            String opinion = (String) payload.get("opinion");
            
            boolean success = adminGoodsService.deleteGoods(gid, opinion);
            CustomResponse response = new CustomResponse();
            if (success) {
                response.setCode(200);
                response.setMessage("商品删除成功");
            } else {
                response.setCode(500);
                response.setMessage("操作失败");
            }
            return response;
        } catch (Exception e) {
            CustomResponse response = new CustomResponse();
            response.setCode(500);
            response.setMessage("操作失败: " + e.getMessage());
            return response;
        }
    }
}